package com.mission.schedule.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lcf.refreshlibrary.ILoadingLayout;
import com.lcf.refreshlibrary.PullToRefreshBase;
import com.lcf.refreshlibrary.PullToRefreshScrollView;
import com.mission.schedule.R;
import com.mission.schedule.activity.FriendsSouSuoActivity;
import com.mission.schedule.activity.MyFriendsAppActivity;
import com.mission.schedule.activity.NewSendMessageToFriendActivity;
import com.mission.schedule.adapter.MyFriendsFragmentAdapter;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.FriendsBackBean;
import com.mission.schedule.bean.FriendsBean;
import com.mission.schedule.bean.MyFriendsNewBean;
import com.mission.schedule.bean.SuccessOrFailBean;
import com.mission.schedule.bean.TotalFriendsCountBean;
import com.mission.schedule.bean.WeiDuFriendsBean;
import com.mission.schedule.constants.FristFragment;
import com.mission.schedule.constants.PostSendMainActivity;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.db.DBHelper;
import com.mission.schedule.entity.FriendsTable;
import com.mission.schedule.fragment.BaseFragment;
import com.mission.schedule.my160920.FrendBean;
import com.mission.schedule.my160920.NewEndTaskActivity;
import com.mission.schedule.my160920.NewMyFragment;
import com.mission.schedule.my160920.ScrollLinearLayoutManager;
import com.mission.schedule.my160920.adapter.FindFrendAdapter;
import com.mission.schedule.my160920.bean.FriendBackBean;
import com.mission.schedule.my160920.bean.FriendBean;
import com.mission.schedule.my160920.bean.FriendDeleteScheduleBean;
import com.mission.schedule.my160920.bean.FriendDownAllScheduleBean;
import com.mission.schedule.my160920.bean.FriendDownBackBean;
import com.mission.schedule.my160920.bean.LyNewNumBean;
import com.mission.schedule.my160920.widget.OnRefreshRecyclerViewHeader;
import com.mission.schedule.swipexlistview.MySwipeXListView;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.NetUtil.NetWorkState;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.PullToRefreshViewNoFooter;
import com.mission.schedule.utils.PullToRefreshViewNoFooter.OnFooterRefreshListener;
import com.mission.schedule.utils.PullToRefreshViewNoFooter.OnHeaderRefreshListener;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.Utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import de.greenrobot.event.EventBus;

/**
 * Created by liwei on 2017/2/17.
 */

public class NewMyActivity extends BaseActivity implements OnClickListener{

    //结束任务回调
    private static int END_RESULT = 901;
    //添加好友回调
    private static int ADD_PERSON_RESULT = 902;
    //留言回调
    private static int LY_RESULT = 903;

    private boolean isShow = false;// 判断是否已经显示
    public static LinearLayout top_ll_back;
    RelativeLayout my_friend_ll_right;

    SharedPrefUtil sharedPrefUtil = null;
    String userID = "0";
    public static final int ADDFRIEND = 2;
    public static final int CHECKFRIEND = 4;

    String myfriendscount;
    LinearLayout add_rl;
    RelativeLayout re_re;

    /**
     * 2016-09-20 新的布局
     */
    private RecyclerView mRecyclerView;
    //适配器
    private FindFrendAdapter findFrendAdapter;
    //组合bean
    private List<FrendBean> frendBeanList;
    //好友bean
    private List<FriendBean> friendBeanList;
    //下行日程bean
    private List<FriendDownAllScheduleBean> firendDownBeanList;

    private List<FriendDeleteScheduleBean> friendDeleteScheduleBeanList;

//    private SwipeRefreshLayout swipeRefreshLayout;

    String updatetime = "2016-01-01";
    String persondowntime = "2016-01-01";

    private LinearLayout myfriend_ll;
    private boolean lytype = false;
    PullToRefreshScrollView pull_refresh_scrollview;

    lybo lyb;
    addp add;
    
    Context context;

    @Override
    protected void setListener() {

    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.fragment_myfriend);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isApplicationBroughtToBackground(context)) {
            if (lytype == false) {
                DownFrendCalenderLy();
            }
            lytype = false;
        }
        DBtoAllList();
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        context = this;
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        userID = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.USERID, "0");
        persondowntime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.PERSONDOWNTIME, "2016-01-01");
        myfriendscount = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.COUNT, "0");
        updatetime = sharedPrefUtil.getString(context,
                ShareFile.USERFILE, ShareFile.UPDATESETTIME, "2016-01-01");

        re_re = (RelativeLayout) findViewById(R.id.re_re);
        top_ll_back = (LinearLayout) findViewById(R.id.top_ll_back);
        top_ll_back.setOnClickListener(this);
        myfriend_ll = (LinearLayout) findViewById(R.id.myfriend_ll);
        myfriend_ll.setOnClickListener(this);
        my_friend_ll_right = (RelativeLayout) findViewById(R.id.my_friend_ll_right);
        my_friend_ll_right.setOnClickListener(this);
        add_rl = (LinearLayout) findViewById(R.id.add_rl);
        add_rl.setOnClickListener(this);

        /**
         * 2016-9-20
         */

        pull_refresh_scrollview = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
        pull_refresh_scrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
                    DownFrend();
                } else {
                    Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                    pull_refresh_scrollview.onRefreshComplete();
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

            }
        });
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recylerview);
        mRecyclerView.setNestedScrollingEnabled(false);

        mRecyclerView.setHasFixedSize(true);
        frendBeanList = new CopyOnWriteArrayList<>();
        listBeanList = new ArrayList<>();


        findFrendAdapter = new FindFrendAdapter(frendBeanList, context, handler);

        final ScrollLinearLayoutManager scrollLinearLayoutManager = new ScrollLinearLayoutManager(context);
        mRecyclerView.setLayoutManager(scrollLinearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(findFrendAdapter);


//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                int topRowVerticalPosition =
//                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
//                toLoadLayout.setRefreshEnabled(topRowVerticalPosition >= 0);
//            }
//
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//            }
//        });


        /**
         * end
         */
        lyb = new lybo();
        IntentFilter ifd = new IntentFilter();
        ifd.addAction("ly");
        registerReceiver(lyb, ifd);
        add = new addp();
        IntentFilter addifd = new IntentFilter();
        addifd.addAction("add");
        registerReceiver(add, addifd);

        DBtoAllList();

        /**
         * 检查是否有发出的6.0.0版本的表,没有则创建
         */
        DBHelper helper = new DBHelper(context);
        if (!helper.tabIsExist("FriendsListTable")
                && !helper.tabIsExist("FriendDownAllScheduleBean")
                && !helper.tabIsExist("FriendCommonReply")) {
            App.getDBcApplication().createTbale();
            updatetime = "2016-01-01";
            persondowntime = "2016-01-01";
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    DownFrend();
                }
            }, 2000);
        } else {
            DownFrendCalenderLy();
        }
    }

    @Override
    protected void setAdapter() {

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 3:
                    sendMess(4);
                    if (frendBeanList.size() > 0) {
                        re_re.setVisibility(View.VISIBLE);
                        add_rl.setVisibility(View.GONE);
                    } else {
                        add_rl.setVisibility(View.VISIBLE);
                        re_re.setVisibility(View.GONE);
                    }
                    findFrendAdapter = new FindFrendAdapter(frendBeanList, context, handler);
                    mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
                    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
                    mRecyclerView.setAdapter(findFrendAdapter);
                    break;
                case 4:

                    pull_refresh_scrollview.onRefreshComplete();
                    break;
                case 5:
                    cpidhandler = msg.arg1 + "";
                    DownFrendCalenderLy();
                    break;
                case 6:
                    cpidhandler = msg.arg2 + "";
                    frendBeanList.get(Integer.valueOf(msg.obj + "")).setCount(0);
                    lytype = true;
                    break;
                case 8:
                    add_rl.setVisibility(View.VISIBLE);
                    re_re.setVisibility(View.GONE);
                    break;
                case 9:
                    DownFrendCalenderLy();
                    break;
                case 100:
                    DownFrend();
                    break;
            }
        }

    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_friend_ll_right:// 添加好友
                startActivityForResult(new Intent(context,
                        FriendsSouSuoActivity.class), ADDFRIEND);
                break;
            case R.id.friendapplication_ll:// 查看申请的好友
                startActivityForResult(new Intent(context,
                        MyFriendsAppActivity.class), CHECKFRIEND);
                break;
            case R.id.add_rl:
                startActivityForResult(new Intent(context,
                        FriendsSouSuoActivity.class), ADDFRIEND);
                break;
            case R.id.top_ll_back:
                onBackPressed();
                break;
            case R.id.myfriend_ll:
                alterImportantDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADDFRIEND) {
            if (resultCode == Activity.RESULT_OK) {
                if (data.getStringExtra("cpidhandler") != null) {
                    cpidhandler = data.getStringExtra("cpidhandler");
                }
                DownFrend();
            }
        } else if (requestCode == END_RESULT) {
            if (resultCode == Activity.RESULT_OK) {
                DownFrend();
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                DBtoAllList();
            }
        } else if (requestCode == ADD_PERSON_RESULT) {
            if (resultCode == Activity.RESULT_OK) {

            }
        } else if (requestCode == LY_RESULT) {
            if (resultCode == Activity.RESULT_OK) {
                DownFrend();
            }
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        App.getHttpQueues().cancelAll("down");
        handler.removeCallbacksAndMessages(null);
        if (lyb != null) {
            context.unregisterReceiver(lyb);
        }
        if (add != null) {
            context.unregisterReceiver(add);
        }
        super.onDestroy();
    }


    /**
     * 2016 09 20
     */
    List<Integer> uid = new ArrayList<>();
    List<Integer> numid = new ArrayList<>();


    class dbToAllList extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] objects) {
            DownFrendCalenderLy();
            return null;
        }
    }


    private List<String> uidpx = new ArrayList<>();
    //
    private String cpidhandler = "";
    /**
     * 将数据库的数据转换为一个Bean
     */
    private void DBtoAllList() {
        List<FriendBean> friendBeanList = App.getDBcApplication().backFriendsList(userID);
        List<FriendDownAllScheduleBean> friendDownAllScheduBeanList = App.getDBcApplication().getAllFriendSchedule();
        frendBeanList.clear();

        if (friendBeanList.size() == 0) {
            Log.e("TAG","1");
            pull_refresh_scrollview.onRefreshComplete();
            DownFrend();
        }

        //那些好友有日程
        for (int i = 0; i < friendBeanList.size(); i++) {
            for (int l = 0; l < friendDownAllScheduBeanList.size(); l++) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy0MM0dd");
                Date date = new Date(System.currentTimeMillis());

                int d1 = Integer.valueOf(df.format(date).trim());
                String cda = friendDownAllScheduBeanList.get(l).cdate;
                int d2 = Integer.valueOf(cda.trim().replace('-','0'));

                if (!friendDownAllScheduBeanList.get(l).poststate.equals("2") && d1- d2 >= 0) {
                    if (friendBeanList.get(i).getCpId().equals(friendDownAllScheduBeanList.get(l).getCpId())) {
                        uidpx.add(friendBeanList.get(i).getCpId());
                        break;
                    }
                }

            }
        }
        //更新好友列表,有日程的在前面
        for (int i = 0; i < uidpx.size(); i++) {
            for (int h = 0; h < friendBeanList.size(); h++) {
                if (friendBeanList.get(h).getCpId().equals(uidpx.get(i))) {
                    friendBeanList.add(0, friendBeanList.get(h));
                    friendBeanList.remove(h + 1);
                    break;
                }
            }
        }

        //更新好友列表,有日程新消息的在前面
        for (int h = 0; h < friendBeanList.size(); h++) {
            for (int i = 0; i < friendDownAllScheduBeanList.size(); i++) {
                for (int k = 0; k < listBeanList.size(); k++) {
                    if (friendDownAllScheduBeanList.get(i).getId().equals(listBeanList.get(k).getZId())
                            && listBeanList.get(k).getCount() > 0
                            && friendBeanList.get(h).getCpId().equals(friendDownAllScheduBeanList.get(i).getCpId())) {
                        friendBeanList.add(0, friendBeanList.get(h));
                        friendBeanList.remove(h + 1);
                    }
                }
            }
        }

        //将新增加的日程用户添加到第一位
        if (!cpidhandler.equals("")) {
            for (int i = 0; i < friendBeanList.size(); i++) {
                if (cpidhandler.equals(friendBeanList.get(i).getCpId())) {
                    friendBeanList.add(0, friendBeanList.get(i));
                    friendBeanList.remove(i + 1);
                }
            }
        }

        for (int i = 0; i < friendBeanList.size(); i++) {
            /**
             * uid : 52432
             * id : 767
             * cpId : 260975
             * uPersontag : 加油加油！
             * uToCode : web
             * remark : null
             * uPortrait : 20150925136/638645.jpg
             * dateUpdate : 2016-09-14T10:58:03
             * uNickName : 韩雪h
             * type : 0
             * uBackgroundImage : 20160820/933727.png
             */

            FrendBean frendBean = new FrendBean();

            frendBean.setF_uNickName(friendBeanList.get(i).getuNickName());
            frendBean.setF_uPersontag(friendBeanList.get(i).getuPersontag());
            frendBean.setF_uPortrait(friendBeanList.get(i).getuPortrait());
            frendBean.setF_uToCode(friendBeanList.get(i).getuToCode());
            frendBean.setF_type(friendBeanList.get(i).getType());
            frendBean.setF_uBackgroundImage(friendBeanList.get(i).getuBackgroundImage());
            frendBean.setF_remark(friendBeanList.get(i).getRemark());
            frendBean.setF_dateUpdate(friendBeanList.get(i).getDateUpdate());
            frendBean.setF_cpId(friendBeanList.get(i).getCpId());
            frendBean.setF_id(friendBeanList.get(i).getId());
            frendBean.setF_uid(friendBeanList.get(i).getUid());

            frendBean.setViewType(1);
            frendBean.setUid(friendBeanList.get(i).uid);
            frendBeanList.add(frendBean);
            /**
             * 相同的日程
             */
            for (int j = 0; j < friendDownAllScheduBeanList.size(); j++) {
                if (friendBeanList.get(i).getCpId().equals(friendDownAllScheduBeanList.get(j).getCpId())) {
                    uid.add(j);
                }

            }

            try {
                if (uid.size() <= 0 || uid == null) {
                    FrendBean frendBean4 = new FrendBean();
                    frendBean4.setUid(friendBeanList.get(i).getUid());
                    frendBean4.setF_uNickName(friendBeanList.get(i).getuNickName());
                    frendBean4.setF_uPortrait(friendBeanList.get(i).getuPortrait());
                    frendBean4.setF_cpId(friendBeanList.get(i).getCpId());
                    frendBean4.setCpId(friendBeanList.get(i).getCpId());
                    frendBean4.setViewType(4);
                    frendBeanList.add(frendBean4);
                } else {
                    List<FriendDownAllScheduleBean> friendList = new ArrayList<>();
                    for (int u = 0; u < uid.size(); u++) {
                        friendList.add(friendDownAllScheduBeanList.get(uid.get(u)));
                    }

                    Comparator<FriendDownAllScheduleBean> comparator = new Comparator<FriendDownAllScheduleBean>() {
                        @Override
                        public int compare(FriendDownAllScheduleBean lhs, FriendDownAllScheduleBean rhs) {
                            return rhs.id.compareTo(lhs.id);
                        }
                    };

                    Collections.sort(friendList, comparator);
                    int diffnum = 0;
                    int difnum = 0;
                    List<Integer> us = new ArrayList<>();
                    for (int u = 0; u < friendList.size(); u++) {
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = new Date(System.currentTimeMillis());

                        Date d1 = df.parse(df.format(date));
                        Date d2 = df.parse(friendList.get(u).cdate);
                        long diff = d1.getTime() - d2.getTime();
                        if (!friendList.get(u).poststate.equals("2") || diff <= 0) {
                            difnum++;
                            us.add(u);
                        }
                    }

                    for (int u = 0; u < friendList.size(); u++) {

                        /**
                         * CAlarmsound : g_220* CAlarmsoundDesc : 短提示音* CLightAppId : 0* COpenstate : 0
                         * CPostpone : 1* CRecommendName : 张力川* CTags :* CType : 0* CTypeDesc :* CTypeSpare :* atype : 0* calendaId : 0* cbeforTime : 0
                         * * cdate : 2016-09-19* changTime : 2016-09-19T11:04:53* cisAlarm : 1* cpId : 232380* cretetime : 2016-09-19T11:04:51
                         * ctime : 09:58* downNum : 1* downstate : 0* endNum : 0* endState : 0* id : 396* imgPath :
                         * lyNum : 10* message : 已结束=0/1 一直不准确，不及时。需测试解决。* parReamrk :* pid : 0* poststate : 0* remark :* remark1 :
                         * remark2 :* remark3 :* repCalendaState : 0* repCalendaTime :* repColorType : 0* repDisplayTime : 0
                         * repInStable : 1* repIsPuase : 0* repState : 0* repType : 0* repTypeParameter :* repdatetwo :
                         * repinitialcreatedtime :* replastcreatedtime :* repnextcreatedtime :* repstartdate :* repstatetwo : 0
                         * schIsImportant : 0* status : 1* uid : 52432* webUrl :
                         */

                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = new Date(System.currentTimeMillis());

                        Date d1 = df.parse(df.format(date));
                        Date d2 = df.parse(friendList.get(u).cdate);
                        long diff = d1.getTime() - d2.getTime();


                        if (!friendList.get(u).poststate.equals("2") || diff <= 0) {

                            FrendBean frendBean2 = new FrendBean();

                            frendBean2.setF_uNickName(friendBeanList.get(i).uNickName);
                            frendBean2.setF_uPortrait(friendBeanList.get(i).uPortrait);

                            frendBean2.setCAlarmsound(friendList.get(u).CAlarmsound);
                            frendBean2.setCAlarmsoundDesc(friendList.get(u).CAlarmsoundDesc);
                            frendBean2.setCLightAppId(friendList.get(u).CLightAppId);
                            frendBean2.setCOpenstate(friendList.get(u).COpenstate);
                            frendBean2.setCPostpone(friendList.get(u).CPostpone);
                            frendBean2.setCRecommendName(friendList.get(u).CRecommendName);
                            frendBean2.setCTags(friendList.get(u).CTags);
                            frendBean2.setCType(friendList.get(u).CType);
                            frendBean2.setCTypeSpare(friendList.get(u).CTypeSpare);
                            frendBean2.setAtype(friendList.get(u).atype);
                            frendBean2.setCalendaId(friendList.get(u).calendaId);
                            frendBean2.setCbeforTime(friendList.get(u).cbeforTime);
                            frendBean2.setCdate(friendList.get(u).cdate);
                            frendBean2.setChangTime(friendList.get(u).changTime);
                            frendBean2.setCisAlarm(friendList.get(u).cisAlarm);
                            frendBean2.setCpId(friendList.get(u).cpId);
                            frendBean2.setCretetime(friendList.get(u).cretetime);
                            frendBean2.setCtime(friendList.get(u).ctime);
                            frendBean2.setDownNum(friendList.get(u).downNum);
                            frendBean2.setEndNum(friendList.get(u).endNum);
                            frendBean2.setDownstate(friendList.get(u).downstate);
                            frendBean2.setId(friendList.get(u).id);
                            frendBean2.setImgPath(friendList.get(u).imgPath);
                            frendBean2.setLyNum(friendList.get(u).lyNum);
                            frendBean2.setMessage(friendList.get(u).message);
                            frendBean2.setParReamrk(friendList.get(u).parReamrk);
                            frendBean2.setPoststate(friendList.get(u).poststate);
                            frendBean2.setPid(friendList.get(u).pid);
                            frendBean2.setRemark(friendList.get(u).remark);
                            frendBean2.setRemark1(friendList.get(u).remark1);
                            frendBean2.setRemark2(friendList.get(u).remark2);
                            frendBean2.setRemark3(friendList.get(u).remark3);
                            frendBean2.setRepCalendaState(friendList.get(u).repCalendaState);
                            frendBean2.setRepCalendaTime(friendList.get(u).repCalendaTime);
                            frendBean2.setRepColorType(friendList.get(u).repColorType);
                            frendBean2.setRepDisplayTime(friendList.get(u).repDisplayTime);
                            frendBean2.setRepInStable(friendList.get(u).repInStable);
                            frendBean2.setRepIsPuase(friendList.get(u).repIsPuase);
                            frendBean2.setRepState(friendList.get(u).repState);
                            frendBean2.setRepType(friendList.get(u).repType);
                            frendBean2.setRepTypeParameter(friendList.get(u).repTypeParameter);
                            frendBean2.setRepdatetwo(friendList.get(u).repdatetwo);
                            frendBean2.setRepinitialcreatedtime(friendList.get(u).repinitialcreatedtime);
                            frendBean2.setReplastcreatedtime(friendList.get(u).replastcreatedtime);
                            frendBean2.setRepnextcreatedtime(friendList.get(u).repnextcreatedtime);
                            frendBean2.setRepstartdate(friendList.get(u).repstartdate);
                            frendBean2.setRepstartdate(friendList.get(u).repstatetwo);
                            frendBean2.setSchIsImportant(friendList.get(u).schIsImportant);
                            frendBean2.setStatus(friendList.get(u).status);
                            frendBean2.setUid(friendList.get(u).uid);
                            frendBean2.setWebUrl(friendList.get(u).webUrl);
                            frendBean2.setRepState(friendList.get(u).repState);
                            frendBean2.setRepState(friendList.get(u).repState);
                            frendBean2.setCount(0);
                            frendBean2.setCids("");
                            frendBean2.setZids("");
                            for (int b = 0; b < listBeanList.size(); b++) {
                                if (friendList.get(u).getId().equals(listBeanList.get(b).getZId())
                                        && listBeanList.get(b).getCount() > 0) {
                                    frendBean2.setCount(1);
                                    frendBean2.setZids(listBeanList.get(b).getZId());
                                }
                            }

                            for (int l = 0 ;l<us.size();l++){
                                if (u == us.get(l)){
                                    if (l == us.size() - 1){
                                        frendBean2.setViewType(3);
                                    }else {
                                        frendBean2.setViewType(2);
                                    }
                                }
                            }

                            frendBeanList.add(frendBean2);
                        } else {
                            diffnum++;
                            if (diffnum == friendList.size()) {
                                FrendBean frendBean4 = new FrendBean();
                                frendBean4.setUid(friendBeanList.get(i).getUid());
                                frendBean4.setF_uNickName(friendBeanList.get(i).getuNickName());
                                frendBean4.setF_uPortrait(friendBeanList.get(i).getuPortrait());
                                frendBean4.setF_cpId(friendBeanList.get(i).getCpId());
                                frendBean4.setCpId(friendBeanList.get(i).getCpId());
                                frendBean4.setViewType(4);
                                frendBeanList.add(frendBean4);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            uid.clear();
            numid.clear();

        }
        sendMess(3);
    }

    private long timetolong(String time) {
        Date d1 = null;
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            d1 = df.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d1.getTime();
    }

    private void sendMess(int what) {
        Message message = new Message();
        message.what = what;
        handler.sendMessage(message);
    }


    /**
     * 下载好友信息
     */
    public void DownFrend() {
        if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
            StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST+"/appFrends_findFrendsSay.do",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String result) {
                            if (!TextUtils.isEmpty(result)) {
                                try {
                                    Log.e("TAG", result);
                                    Gson gson = new Gson();

                                    FriendBackBean friendBackBean = gson.fromJson(result, FriendBackBean.class);
                                    if (friendBackBean.status == 0) {
                                        sharedPrefUtil.putString(context,
                                                ShareFile.USERFILE, ShareFile.UPDATESETTIME, DateUtil.formatDate(new Date()));
                                        friendBeanList = friendBackBean.list;
//                                        App.getDBcApplication().clearFriendsListTable();
                                        if (friendBeanList != null) {

                                            for (FriendBean bean : friendBeanList) {
                                                App.getDBcApplication().insertFriendsList(bean);
                                            }

                                        }
                                        DownFrendCalender();

                                    } else {
                                        sendMess(004);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    sendMess(004);
                                }
                            }
                        }

                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.d("TAG", "error:" + volleyError.toString());
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<>();
                    map.put("uId", userID);// "52432"
                    map.put("updateTime", updatetime);//"2015-01-01 00:00:00"
                    return map;
                }
            };
            stringRequest.setTag("friend");
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
            App.queues.add(stringRequest);
        } else {
            Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
//            swipeRefreshLayout.setRefreshing(false);
            pull_refresh_scrollview.onRefreshComplete();
        }
    }


    /**
     * 下载所有日程信息
     */
    public void DownFrendCalender() {
        StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST+"/appFrends_downFrendsCalendar.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();

                                FriendDownBackBean findFrendsSayBean = gson.fromJson(result, FriendDownBackBean.class);
                                Log.e("TAG", result);
                                if (findFrendsSayBean.status == 0) {

                                    sharedPrefUtil
                                            .putString(
                                                    context,
                                                    ShareFile.USERFILE,
                                                    ShareFile.PERSONDOWNTIME,
                                                    findFrendsSayBean.downTime.replace('T', ' '));

                                    firendDownBeanList = findFrendsSayBean.list;
                                    friendDeleteScheduleBeanList = findFrendsSayBean.delList;

//                                    App.getDBcApplication().clearFriendDownAllScheduleBea();

                                    if (firendDownBeanList != null) {
                                        for (FriendDownAllScheduleBean bean : firendDownBeanList) {
                                            App.getDBcApplication().insertFriendSchedule(bean);
                                        }
                                        if (friendDeleteScheduleBeanList != null) {
                                            for (FriendDeleteScheduleBean bean : friendDeleteScheduleBeanList) {
                                                App.getDBcApplication().deleteFriendSchedule(bean.dataId);
                                            }
                                        }

                                    }
                                    new dbToAllList().execute();
                                } else {
                                    sendMess(004);
                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                                sendMess(004);
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userID);// "52432"
                map.put("updateTime", persondowntime);//"2015-01-01 00:00:00"
                Log.e("TAG", URLConstants.HOST+"/appFrends_downFrendsCalendar.do?uId=" + userID + "&updateTime=" + persondowntime);
                return map;
            }
        };
        stringRequest.setTag("allfriendcalender");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    private List<LyNewNumBean.ListBean> listBeanList;

    /**
     * 查询留言更新数量
     */
    public void DownFrendCalenderLy() {

        StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST+"/appFrends_findLyNewNum.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();
                                Log.d("TAG", result);
                                LyNewNumBean lyNewNum = gson.fromJson(result, LyNewNumBean.class);
                                listBeanList.clear();
                                if (lyNewNum.status == 0) {
                                    listBeanList = lyNewNum.list;
                                    List<FriendDownAllScheduleBean> friendDownAllScheduBeanList = App.getDBcApplication().getAllFriendSchedule();
                                    if (listBeanList.size() > 0 && friendDownAllScheduBeanList.size() > 0) {
                                        for(int i = 0;i < listBeanList.size();i++){
                                            for(int j = 0;j < friendDownAllScheduBeanList.size();j++){
                                                if (listBeanList.get(i).zId.equals(friendDownAllScheduBeanList.get(j).calendaId)){
//                                                    Intent intent = new Intent();
//                                                    intent.setAction("numsn");
//                                                    intent.putExtra("l", 1);
//                                                    context.sendBroadcast(intent);
                                                    break;
                                                }
                                            }
                                        }
                                    }
//                                    else {
//                                        Intent intent = new Intent();
//                                        intent.setAction("numsn");
//                                        intent.putExtra("l", 2);
//                                        context.sendBroadcast(intent);
//                                    }
                                    DBtoAllList();
                                }
//                                else {
//                                    Intent intent = new Intent();
//                                    intent.setAction("numsn");
//                                    intent.putExtra("l", 2);
//                                    context.sendBroadcast(intent);
//                                    DBtoAllList();
//                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                sendMess(004);
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
                sendMess(004);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userID);
                map.put("type", "0");
                return map;
            }
        };
        stringRequest.setTag("findLyNewNum");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }


    /**
     * 点击头部，弹出已结束任务，取消布局
     */
    private void alterImportantDialog() {
        Dialog dialog = new Dialog(context, R.style.dialog_translucent_adjustPan);
        Window window = dialog.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.new_my_title_dialog, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.show();

        new alterImportantDialogOnClick(dialog, more_pop_menu);
    }

    class alterImportantDialogOnClick implements OnClickListener {

        private View view;
        private Dialog dialog;
        private TextView stop_tv;
        private TextView canel_tv;

        @SuppressLint("NewApi")
        public alterImportantDialogOnClick(Dialog dialog, View view) {
            this.dialog = dialog;
            this.view = view;
            initview();
        }

        private void initview() {
            stop_tv = (TextView) view.findViewById(R.id.stop_tv);
            stop_tv.setOnClickListener(this);
            canel_tv = (TextView) view.findViewById(R.id.canel_tv);
            canel_tv.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.stop_tv:
                    Intent intent = new Intent(context, NewEndTaskActivity.class);
                    startActivityForResult(intent, END_RESULT);
                    dialog.dismiss();
                    break;
                case R.id.canel_tv:
                    dialog.dismiss();
                    break;
            }
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (!isApplicationBroughtToBackground(context)) {
            DownFrendCalenderLy();
        }
    }

    /**
     * 判断当前应用程序处于前台还是后台
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    class lybo extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Integer.valueOf(intent.getExtras().get("l").toString()) == 1) {
                DownFrend();
            }
        }
    }

    class addp extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getExtras().get("cpid") != null) {
                cpidhandler = intent.getExtras().get("cpid").toString();
                DownFrendCalenderLy();
            }
        }
    }
}
